const SETTING = require('./src/settings.js')
const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const name = SETTING.title || '平台系统' // 网页标题
const isProd = process.env.NODE_ENV === 'production' // 区分环境
const avueVersion = require('./src/avue-version.js')
const cdn = {
  css: [
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/element-ui/2.15.7/lib/theme-chalk/index.css',
    `https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/avue/${avueVersion}/lib/index.css`
  ],
  js: [
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/vue/2.6.12/dist/vue.min.js',
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/vue-router/3.4.9/dist/vue-router.min.js',
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/vuex/3.6.0/dist/vuex.min.js',
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/element-ui/2.15.7/lib/index.js',
    `https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/avue/${avueVersion}/lib/avue.min.js`,
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/echarts/5.4.0/dist/echarts.min.js',
    'https://ihaiking.oss-cn-shanghai.aliyuncs.com/cdn/echarts-gl/2.0.9/dist/echarts-gl.min.js'
  ]
}
// 全局样式配置
// const exportScss = Object.keys(SETTING)
//   .filter((i) => i.match(/\$/))
//   .map((k) => `${k}: ${SETTING[k]};`)
//   .join("\n");
function resolve(dir) {
  return path.join(__dirname, dir)
}
module.exports = {
  outputDir: `dist`,
  runtimeCompiler: true,
  publicPath: '/',
  assetsDir: 'static',
  lintOnSave: true,
  productionSourceMap: false,
  devServer: {
    open: true,
    port: process.env.VUE_APP_PORT,
    host: process.env.VUE_APP_HOST,
    proxy: {
      '/api': {
        target: process.env.VUE_APP_BASE_API, // 本地
        secure: false, // false为http访问，true为https访问
        changeOrigin: true, // 跨域访问设置，true代表跨域
        // logLevel: "debug",
        pathRewrite: {
          // 路径改写规则
          '^/api': ''
        }
        // 设置代理请求头（后端做了host的 *.tim-test.haiking.tech:8889的拦截，所以在代理请求添加对应的域名，实现前端调试，否则所有请求无法通过）
        // haijin.tim-test.haiking.tech:8889,后端会取到租户为haijin，如果是其他租户如t1，则改为：t1.tim-test.haiking.tech:8889
        // 和后端联调，指定网关地址进行代理时，使用该配置，避免后端改域名验证
        // onProxyReq: (proxyReq, req, res) => {
        //   proxyReq.setHeader('Host', 'nthsjmsa.test.ixunhang.com')
        // }
      },
      '/gisws': {
        // webSocket代理
        target: process.env.VUE_APP_WEBSOCKET,
        ws: true, // 开启ws
        changeOrigin: true
        // pathRewrite: {
        //   "^/gisws": "",
        // },
      }
    },
    disableHostCheck: true
  },
  css: {
    loaderOptions: {
      sass: {
        sassOptions: {
          outputStyle: 'expanded'
        }
        // additionalData: `@import "@/assets/styles/mixin.scss";\n${exportScss}`,
      }
    }
  },
  configureWebpack: (config) => {
    config.name = name
    config.module.rules.push({
      test: /\.worker.js$/,
      use: {
        loader: 'worker-loader',
        options: { inline: 'no-fallback' }
      }
    })
    if (isProd) {
      // TODO 打包cdn 上传项目文件
      config.resolve.extensions = ['.js', '.json', '.vue', '.scss', '.css']

      // 打包cdn 上传项目文件
      config.externals = {
        vue: 'Vue',
        'vue-router': 'VueRouter',
        vuex: 'Vuex',
        echarts: 'echarts',
        'echarts-gl': { root: ['echarts-gl'] },
        'element-ui': 'ELEMENT',
        // "@haiking/micro-common": "micro",
        '@haiking/avue': 'AVUE'
      }
      config.plugins.push(
        new CompressionPlugin({
          test: /\.(js|css|html)?$/i, // 压缩文件格式
          filename: '[path].gz[query]', // 压缩后的文件名
          algorithm: 'gzip', // 使用gzip压缩
          minRatio: 0.8 // 压缩率小于1才会压缩
        })
      )
      config.plugins.push(
        new TerserPlugin({
          terserOptions: {
            ie8: true,
            warnings: true,
            output: {
              comments: false,
              beautify: false
            },
            compress: {
              drop_console: true,
              pure_funcs: [] // 移除console
            }
          }
        })
      )
      config['performance'] = {
        maxEntrypointSize: 10000000,
        maxAssetSize: 30000000
      }
    }
  },
  chainWebpack(config) {
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')

    // 压缩图片
    config.module
      .rule('images')
      .use('url-loader')
      .loader('url-loader')
      .tap((options) =>
        Object.assign(options, {
          limit: 20000
        })
      )
    // set svg-sprite-loader
    // config.module.rule("svg").exclude.add(resolve("src/assets/icons")).end();
    // config.module
    //   .rule("icons")
    //   .test(/\.svg$/)
    //   .include.add(resolve("src/assets/icons"))
    //   .end()
    //   .use("svg-sprite-loader")
    //   .loader("svg-sprite-loader")
    //   .options({
    //     symbolId: "icon-[name]",
    //   })
    //   .end();
    config.module
      .rule('fonts')
      .test(/.(ttf|otf|eot|woff|woff2)$/)
      .use('url-loader')
      .loader('url-loader')
      .options({})
      .end()
    config.when(isProd, (config) => {
      config
        .plugin('html')
        .tap((args) => {
          args[0].cdn = cdn
          return args
        })
        .end()
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          }
        }
      })
      config.optimization.runtimeChunk('single'),
        {
          from: path.resolve(__dirname, './public/robots.txt'), // 防爬虫文件
          to: './' // 到根目录下
        }
    })
  },
  parallel: false
}
